package com.coalmine.api.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.coalmine.api.annotation.LoginRequired;
import com.coalmine.common.constant.Constants;
import com.coalmine.common.constant.CacheConstants;
import com.coalmine.common.constant.HttpStatus;
import com.coalmine.common.core.redis.RedisCache;
import com.coalmine.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 资源服务目录登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {



    private RedisCache redisCache;


    public LoginInterceptor(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否存在注解
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod method = (HandlerMethod)handler;
        boolean hasLoginAnnotation=method.getMethod().isAnnotationPresent(LoginRequired.class);
        if(!hasLoginAnnotation){
            //不存在LoginRequired注解，则直接通过
            return true;
        }
        LoginRequired loginRequired=method.getMethod().getAnnotation(LoginRequired.class);
        //2.required=false,则无需检查是否登录
        if(!loginRequired.required()){
            return true;
        }
        //3.登录状态检查,使用response返回指定信息
        String header = request.getHeader("id");
        if (StringUtils.isEmpty(header)) {
            return false;
        }
        String cacheKey = CacheConstants.USER_TOKEN + ":" + header;
        String cacheToken = redisCache.getCacheObject(cacheKey);
        if (StringUtils.isNotNull(cacheToken)){
            return true;
        }
        JSONObject json = new JSONObject();
        json.put("code", HttpStatus.UNAUTHORIZED);
        json.put("msg", "无权访问资源，请登录!!!");
        //设置编码格式
        response.setCharacterEncoding(Constants.UTF8);
        response.setContentType(Constants.ContentType);
        response.getWriter().append(json.toString());
        return false;
    }
}
